import { forwardRef, Inject, Injectable, OnModuleInit } from "@nestjs/common";
import { configuration } from "../../../../config/config";
import * as net from "node:net";
import { HardwareService } from "../hardware.service";

@Injectable()
export class TransportClientService implements OnModuleInit {
  private client;

  constructor(
    @Inject(forwardRef(() => HardwareService))
    private readonly hardwareService: HardwareService,
  ) {}

  connect() {
    return new Promise((resolve, reject) => {
      this.client = new net.Socket();
      this.client.connect(
        configuration.hardwareServer.hardware_port,
        configuration.hardwareServer.hardware_ip,
      );
      this.client.setTimeout(10000); // 这个超时时间就是如果没有消息。会出发timeout的时间。

      this.client.on("connect", (err) => {
        console.log("hardware与mock server连接成功");
      });
      this.client.on("finish", () => {
        console.log("finish");
      });
      this.client.on("timeout", (err) => {
        console.log("timeout", err);
        reject(err);
      });
      this.client.on("data", async (data) => {
        resolve("");
        this.receiveData(data);
      });
      this.client.on("error", (err) => {
        reject(err);
      });
    });
  }

  receiveData(data) {
    this.broadcastMsg(data);
  }

  broadcastMsg(data) {
    this.hardwareService.broadcastMsg(data);
  }

  sendMsg2Machine(msg) {
    console.log(`socket 客户端向 服务端发送消息：${msg}`);
    this.client.write(msg);
  }

  async onModuleInit(): Promise<any> {
    this.connect();
  }
}
